# -*- coding: utf-8 -*-
import os

import allure
import pytest
from common.driver import Driver
from common.page import Page
from config.config import Config
from time import sleep


@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    out = yield
    report = out.get_result()
    is_setup_teardown = Config().data[Config().data['execute']['project_name']]['is_setup_teardown'] == str(True)

    if report.when == 'setup':
        Page.logger.info("****", extra={'appname': '************************************************************'})
        Page.logger.info("****", extra={'appname': ''})
        Page.logger.info('**** 开始执行用例:%s' % str(item.name), extra={'appname': ''})
        Page.logger.info("****", extra={'appname': ''})
        Page.logger.info("****", extra={'appname': '************************************************************'})
        # if is_setup_teardown:
        #     with allure.step("step：打开登录首页"):
        #         driver = Driver.init_driver()
        #         Driver.get_url(driver, Config().base_url)
        #         # 保障稳定性,还是加了全局等待,牺牲了部分运行效率
        #         driver.implicitly_wait(0.5)

    if report.when == 'teardown':
        Page.logger.info("****", extra={'appname': '************************************************************'})
        Page.logger.info("****", extra={'appname': ''})
        Page.logger.info('**** 用例执行结束:%s' % str(item.name), extra={'appname': ''})
        Page.logger.info("****", extra={'appname': ''})
        Page.logger.info("****", extra={'appname': '************************************************************'})
        # if is_setup_teardown:
        #     with allure.step("step：退出浏览器"):
        #         sleep(2)
        #         Page.quit()

    if report.when == 'call' and report.outcome == 'failed':
        with allure.step('添加失败截图...'):
            allure.attach(Page.driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)


def rerun_times():
    rerun_times = Config().data['rerun_time']
    return int(rerun_times)
